package com.yunfinal.api.tpl.template.directive.db;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.DbPro;
import com.jfinal.template.Directive;
import com.jfinal.template.Env;
import com.jfinal.template.expr.ast.Expr;
import com.jfinal.template.expr.ast.ExprList;
import com.jfinal.template.expr.ast.Id;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.Scope;

import java.util.Objects;

/**
 * 切换数据源
 * #dbConfigName(main)
 *     调用其他查询工具
 * #end
 * @author  杜福忠
 */
public class DbConfigName  extends Directive {
    private final static ThreadLocal<String> TL = new ThreadLocal<>();
    protected String name;

    public static DbPro db(){
        String configName = DbConfigName.get();
        if (Objects.nonNull(configName)){
            return Db.use(configName);
        }
        return Db.use();
    }

    public static String get(){
        return TL.get();
    }

    @Override
    public void setExprList(ExprList exprList) {
        Expr[] exprArray = exprList.getExprArray();
        if (exprArray.length == 0) {
            return;
        }
        if ((exprArray[0] instanceof Id)) {
            this.name = ((Id) exprArray[0]).getId();
        }
    }

    @Override
    public void exec(Env env, Scope scope, Writer writer) {
        TL.set(name);
        try {
            stat.exec(env, scope, writer);
        }finally {
            TL.remove();
        }
    }

    @Override
    public boolean hasEnd() {
        return true;
    }
}
